package com.smxy.hunzi.user.service.impl;

import com.smxy.hunzi.common.utils.Constant;
import com.smxy.hunzi.common.utils.R;
import com.smxy.hunzi.user.utils.JwtUtil;
import com.smxy.hunzi.user.utils.Md5;
import com.smxy.hunzi.user.vo.UserLoginVo;
//import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authc.IncorrectCredentialsException;
//import org.apache.shiro.authc.UnknownAccountException;
//import org.apache.shiro.authc.UsernamePasswordToken;
//import org.apache.shiro.crypto.hash.Md5Hash;
//import org.apache.shiro.subject.Subject;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.beans.Beans;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smxy.hunzi.common.utils.PageUtils;
import com.smxy.hunzi.common.utils.Query;

import com.smxy.hunzi.user.dao.UserDao;
import com.smxy.hunzi.user.entity.UserEntity;
import com.smxy.hunzi.user.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String perms = (String) params.get("perms");
        String userStatus = (String) params.get("userStatus");
       // System.out.println("key:" +key+"   perms"+perms+"   userStatus:"+userStatus);
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(perms))
            wrapper.eq("perms", Integer.parseInt(perms));
        if(!StringUtils.isEmpty(userStatus))
            wrapper.eq("user_status", Integer.parseInt(userStatus));
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w -> {
                w.like("email", key).or().like("nickname", key).or().like("id", key);
            });
        }
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public R register(UserEntity user) {
        UserEntity entity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>()
                .eq("email", user.getEmail()));
        if(entity != null)
            return R.error(Constant.ResponseCode.ERROR_USER_EXIST.getCode(),Constant.ResponseCode.ERROR_USER_EXIST.getMsg());
        String md5Code = Md5.getMd5Code(user.getPassword(), user.getEmail(), 10);
        user.setPassword(md5Code);
        this.save(user);
        return R.ok();
    }

    @Override
    public R login(UserLoginVo userLoginVo) {
        //密码为空
        if(userLoginVo.getPassword() == null)
            return R.error(Constant.ResponseCode.ERROR_USER_WRONG_PASSWORD.getCode(),Constant.ResponseCode.ERROR_USER_WRONG_PASSWORD.getMsg());
        UserEntity entity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>()
                .eq("email", userLoginVo.getEmail()));
        //用户不存在
        if(entity == null){
            return R.error(Constant.ResponseCode.ERROR_USER_NOT_EXIST.getCode(),Constant.ResponseCode.ERROR_USER_NOT_EXIST.getMsg());
        }
        String md5Code = Md5.getMd5Code(userLoginVo.getPassword(), userLoginVo.getEmail(), 10);

        //密码错误
        if(!entity.getPassword().equals(md5Code)){
            return R.error(Constant.ResponseCode.ERROR_USER_WRONG_PASSWORD.getCode(),Constant.ResponseCode.ERROR_USER_WRONG_PASSWORD.getMsg());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("email", entity.getEmail());
        map.put("id", entity.getId() );
        map.put("perms",entity.getPerms() );
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), map, null);
        return R.ok().put("token", token);
    }

    @Override
    public R updateStatus(UserEntity userEntity,String isAdmin,String token)  {
        if("yes".equals(isAdmin)){
            UserEntity entity = new UserEntity();
            entity.setId(userEntity.getId());
            entity.setUserStatus(userEntity.getUserStatus());
            if(entity.getUserStatus() == 1 || entity.getUserStatus() == 2)
                entity.setPerms(0);
            this.updateById(entity);
            return R.ok();
        }else{
            Claims claims = null;
            try {
                claims = JwtUtil.parseJWT(token);
            } catch (Exception e) {
                return R.error(Constant.ResponseCode.TOKEM_INVALID.getCode(), Constant.ResponseCode.TOKEM_INVALID.getMsg() + "------");
            }
            Integer perms = (Integer) claims.get("perms");
            if(perms == 0)
                return R.error(Constant.ResponseCode.USER_NOT_PERMISSION.getCode(),Constant.ResponseCode.USER_NOT_PERMISSION.getMsg());
            UserEntity entity = new UserEntity();
            entity.setId(userEntity.getId());
            entity.setUserStatus(userEntity.getUserStatus());
            if(userEntity.getPerms() == 1)
                return R.error(Constant.ResponseCode.USER_NOT_PERMISSION.getCode(),"无法操作管理员角色");

            this.updateById(entity);
            return R.ok();
        }
    }

    /**
     * 更改用户密码
     *
     * @param userEntity
     * @return
     */
    @Override
    public R updatePassword(UserEntity userEntity) {

        UserEntity entity = new UserEntity();
        String newPassword = Md5.getMd5Code(userEntity.getPassword(), userEntity.getEmail(), 10);
        this.updateById(entity);
        return R.ok();
    }

    @Override
    public R updatePerms(UserEntity userEntity) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(userEntity, entity);
//        entity.setId(userEntity.getId());
//        entity.setPerms(userEntity.getPerms());
        this.updateById(entity);;
        return R.ok();
    }

}